<?php
namespace Ayhome\Suite\Server;

use think\facade\Cache;

use swoole_server;

class Tcp extends \FastD\Swoole\Server\TCP
{

  public function doWork(swoole_server $server, $fd, $data, $from_id)
  {
    Cache::set('tcp_data',$data);
    if ('quit' === $data) {
      $server->close($fd);
      return 0;
    }
    $data =  json_decode($data, true);
    $url = $data['url'];
    if (!$url) {
      $server->close($fd);
      return 0;
    }
    $path_arr = explode("/", $url);
    $action = $path_arr[count($path_arr) - 1];
    $cls = $path_arr[2].'/'.$path_arr[3];


    $post = $data['post'];
    request()->raw = json_encode($data['data']);
    try {
      // print_r(json_encode($data['data']));
      $ret = action($cls, $post, $path_arr[1].'\controller');
      $r = $ret->getContent();
      $r = json_decode($r,true);
      $r['url'] = $url;
      $server->send($fd, json_encode($r));
    } catch (Exception $e) {
      $server->send($fd, $url.$e->getMessage());
    }

    return 0;
  }

  public function doTask(swoole_server $server, $data, $taskId, $workerId)
  {
    echo $data . ' on task' . PHP_EOL;
    return $data;
  }

  public function doFinish(swoole_server $server, $data, $taskId)
  {
    echo $data . 'Finish' . PHP_EOL;
  }
}
